<template>
  <div class="closeAccount">
    <back-nav
      :leftArrow="true"
      :title="'订单结算'"
      :leftText="'返回'"
    ></back-nav>
    <div class="box">
         <div class="selector">
      <div
        :class="['take-out', { active: currentIndex == 0 }]"
        @click="take(0)"
      >
        luckin配送
      </div>
      <div :class="['ask-for', { active: currentIndex == 1 }]" @click="take(1)">
        到店自取
      </div>
    </div>
    <div class="site">
      <div class="icon">
        <img src="../assets/images/place.png" class="auto-img" />
      </div>
      <div class="text">
        <div class="textTop">{{ siteData.address }}</div>
        <div class="textBottom">
          {{ siteData.name }}
          <span class="phone">{{ siteData.tel }}</span>
        </div>
      </div>
      <div class="noText" v-if="isDefault">请添加你的地址</div>
      <div class="default" v-if="defaultFlag">默认</div>
      <div class="rightIcon" @click="detail">
        <img src="../assets/images/right.png" class="auto-img" />
      </div>
    </div>
    <div class="mode">
      <div class="timeIcon">
        <img src="../assets/images/time.png" class="auto-img" />
      </div>
      <div class="text">{{ text }}</div>
      <div class="time">(预计{{ time }}{{ textEnd }})</div>
      <div class="rightIcon">
        <img src="../assets/images/right.png" class="auto-img" />
      </div>
    </div>
    <div class="gift" v-if="isFlag">
      <div class="giftIcon">
        <img src="../assets/images/gift.png" class="auto-img" />
      </div>
      <div class="giftText">新人礼券</div>
      <div class="giftPrice">-￥{{ giftPrice }}</div>
    </div>
    <div class="ItemsTotal">
      <div class="item">
        <div>商品总计</div>
        <div class="price">￥{{ calculate == 0 ? "0" : calculate }}.0</div>
      </div>
      <div class="item" v-if="distributionFlag">
        <div>
          配送费
          <span class="discounts"> (满35免配送费) </span>
        </div>
        <div class="price">￥{{ distributionPrice }}.0</div>
      </div>
      <div class="item">
        <div>优惠券</div>
        <div class="price">-￥{{ isFlag ? giftPrice : 0 }}.0</div>
      </div>
      <div class="item">
        <div>实付金额</div>
        <div class="bigPrice">
          <span class="small">￥</span>
          {{ endPrice == 0 ? 0 : endPrice }}.0
        </div>
      </div>
    </div>
    </div>
    <van-button
      type="primary"
      size="large"
      :round="true"
      color="#2BAB7B"
      @click="settleAccounts"
      >{{payText}}</van-button
    >
    <van-popup
      v-model="showList"
      round
      position="bottom"
      style="height: 40%; padding-top: 4px"
    >
      <van-address-list
        :list="list"
        v-model="chosenAddressId"
        default-tag-text="默认"
        @select="click"
        @add="onAdd"
        @edit="onEdit"
      />
    </van-popup>
    <van-popup
      v-model="payFlag"
      round
      position="bottom"
      style="height: 42%; padding-top: 4px"
    >
      <pay-ment
        @toggle="setPay"
        @remove="remove"
        :num="payNUm"
        :price="endPrice"
      ></pay-ment>
    </van-popup>
  </div>
</template>
<script>
import backNav from "../components/BackNav.vue";
import payMent from "../components/Pay.vue";
export default {
  name: "closeAccount",
  data() {
    return {
      currentIndex: 0,
      //   时间
      time: 0,
      chosenAddressId: "",
      // 文字
      text: "尽快送达",
      textEnd: "送达",
      calculate: 0,
      endPrice: 0,
      isFlag: false,
      siteData: "",
      // 支付的个数
      payNUm:0,
      isDefault:false,
      distributionFlag: true,
      // 配送的渲染
      distribution: "",
      // 默认的状态
      defaultFlag: false,
      // 支付界面
      payFlag: false,
      payText:"立即结算",
      // 弹出框
      showList: false,
      // 配送费的金额
      distributionPrice: 0,
      list: [],
    };
  },
  components: {
    backNav,
    payMent,
  },
  computed: {
    giftPrice() {
      return this.$store.state.discounts;
    },
    newTypeArr() {
      return this.$store.state.allArr;
    },
  },
  methods: {
    take(index) {
      if (index == 1) {
        this.defaultFlag = false;
        this.isDefault=false;
        this.distributionFlag = false;
        this.siteData = {
          address: "广州市天河区黄埔大道西122号之二101房",
          tel: "15173605878",
          name: "瑞幸咖啡天河第三分公司",
        };
        this.text = "尽快取餐";
        this.textEnd = "可取";
        if (this.isFlag) {
          this.endPrice = this.calculate - this.giftPrice;
        } else {
          this.endPrice = this.calculate;
        }
      } else if (index == 0) {
        this.siteData = this.distribution;
        this.distributionFlag = true;
        this.defaultFlag = true;
        this.text = "尽快送达";
        this.textEnd = "送达";
        if (this.isFlag) {
          if (this.calculate >= 35) {
            this.endPrice = this.calculate - this.giftPrice;
          } else {
            this.endPrice =
              this.calculate - this.giftPrice + this.distributionPrice;
          }
        } else {
          if (this.calculate < 35) {
            this.endPrice = this.calculate + this.distributionPrice;
          } else {
            this.endPrice = this.calculate + this.distributionPrice;
          }
        }
      }
      if (this.currentIndex == index) {
        return;
      }
      this.currentIndex = index;
    },
    click(item) {
      this.isDefault=false;
      this.defaultFlag = item.isDefault;
      this.siteData = item;
      this.showList = false;
    },
    // 获取配送时间
    getTime() {
      let time = new Date().toLocaleString("chinese", { hour12: false });
      let hour = "";
      time = time.split(" ")[1].split(":");
      hour = Number(time[0]) + 1;
      if (hour < 10) {
        hour = "0" + hour;
      } else if (hour > 10 && hour < 24) {
        hour = hour;
      } else if (hour > 24) {
        hour = "0" + (hour - 24);
      }
      this.time = `${hour}:${time[1]}`;
    },
    // 订单结算获取的商品
    commitShop() {
      let newTypeArr = this.newTypeArr;
      let commitArr = [];
      let sids = "";
      newTypeArr.forEach((item) => {
        if (item.flag) {
          commitArr.push(item.data.sid);
        }
      });
      sids = JSON.stringify(commitArr);
      this.axios({
        method: "get",
        url: "/commitShopcart",
        params: {
          sids,
        },
      })
        .then((res) => {
          // 计算金额
          if (res.data.code === 50000) {
            res.data.result.forEach((item) => {
              this.calculate += Number(
                (item.count * Number(item.price)).toFixed(2)
              );
            });
            // 配送费
            if (this.calculate > 35) {
              this.distributionPrice = 0;
            } else {
              this.distributionPrice = 5;
            }
            // 计算实际金额
            if (this.isFlag) {
              if (this.calculate >= 35) {
                this.endPrice = this.calculate - this.giftPrice;
              } else {
                this.endPrice =
                  this.calculate - this.giftPrice + this.distributionPrice;
              }
            } else {
              if (this.calculate < 35) {
                this.endPrice = this.calculate + this.distributionPrice;
              } else {
                this.endPrice = this.calculate + this.distributionPrice;
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取地址
    getSite() {
      this.axios({
        method: "get",
        url: "/findAddress",
      })
        .then((res) => {
          let num=0;
          if (res.data.code === 20000) {
            res.data.result.forEach((item) => {
              if (item.isDefault === 1) {
                this.siteData = item;
                // 存储数据方便切换
                this.distribution = item;
                this.defaultFlag = true;
                this.isDefault=false;
              }else{
                 num++;
              }
            });
          }
          // 说明没有默认地址
          if(num==res.data.result.length){
              this.isDefault=true
          }
          let detailSite =
            this.siteData.province +
            this.siteData.city +
            this.siteData.county +
            this.siteData.addressDetail;
          this.siteData.address = detailSite;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    inquireAddress() {
      this.axios({
        method: "get",
        url: "/findAddress",
      })
        .then((res) => {
          if (res.data.code === 20000) {
            let address = "";
            let SiteFlag = "";
            res.data.result.forEach((item) => {
              address =
                item.province +
                item.city +
                item.county +
                " " +
                item.addressDetail;
              if (item.isDefault == 1) {
                SiteFlag = true;
              } else {
                SiteFlag = false;
              }
              this.list.push({
                id: item.id,
                name: item.name,
                tel: item.tel,
                aid: item.aid,
                postalCode: item.postalCode,
                isDefault: SiteFlag,
                address,
              });
            });
            // 设为默认地址
            for (let i = this.list.length - 1; i >= 0; i--) {
              if (this.list[i].isDefault) {
                this.chosenAddressId = this.list[i].id;
                this.list.unshift(this.list[i]);
                this.list.splice(i + 1, 1);
                break;
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onEdit() {},
    detail() {
      if (this.currentIndex == 0) {
        this.showList = true;
      }
    },
    onAdd() {
      this.$router.push({ name: "Site" });
    },
    // 看用户使用了礼券没有
    isUseDiscounts() {
      this.isFlag = window.sessionStorage.getItem("discountsFlag");
    },
    // 结算按钮
    settleAccounts() {
      let num=0;
      this.payFlag = true;
      this.newTypeArr.forEach(item=>{
        if(item.flag){
           num++
        }
      })
      this.payNUm=num
    },
    // 结算
    accounts() {
      let arr = [];
      // 获取到store里面的数组的数据
      this.newTypeArr.forEach((item) => {
        if (item.flag) {
          arr.push(item.data.sid);
        }
      });
      let sids = JSON.stringify(arr);
      this.axios({
        method: "post",
        url: "/pay",
        data: {
          sids,
          phone: this.siteData.tel,
          address: this.siteData.address,
          receiver: this.siteData.name,
        },
      })
        .then((res) => {
          if (res.data.code === 60000) {
            this.$toast(res.data.msg);
          }
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    setPay(flag) {
      this.payFlag = flag;
      // 设置优惠券为无
      if(window.sessionStorage.getItem("discountsFlag")){
          this.$store.commit("setCoupon",-1);
           window.sessionStorage.setItem("useCoupon",true);
          window.sessionStorage.setItem("coupon",null);
      }
      this.accounts();
      this.payText="支付成功"
      setTimeout(() => {
        this.$router.push({ name: "Home" });
      }, 2000);
    },
    remove(flag) {
      this.payFlag = flag;
    },
  },
  created() {
    this.getTime();
    this.commitShop();
    this.isUseDiscounts();
    this.getSite();
    this.inquireAddress();
  },
};
</script>
<style lang="less" scoped>
@import url("../assets/base.less");
.box{
  position: absolute;
  top: 46px;
  width: 100%;
  bottom: 45px;
  overflow-y: auto;
.selector {
  position: relative;
  height: 30px;
  background: #fff;
  padding-left: 20px;
  padding-top: 10px;
  .take-out {
    position: absolute;
    height: 30px;
    width: 102px;
    border-radius: 15px;
    background-color: #fff;
    border: 2px solid @mainColor;
    color: @mainColor;
    font-weight: bold;
    text-align: center;
    line-height: 30px;
    font-size: 12px;
    z-index: 2;
  }
  .ask-for {
    position: absolute;
    height: 30px;
    width: 102px;
    margin-left: 82px;
    border-radius: 15px;
    background-color: #fff;
    border: 2px solid @mainColor;
    color: @mainColor;
    font-weight: bold;
    text-align: center;
    line-height: 30px;
    font-size: 12px;
  }
  .active {
    color: #fff;
    background-color: @mainColor;
    z-index: 20;
  }
}
.site {
  height: 55px;
  padding-top: 80px;
  background-color: #fff;
  display: flex;
  padding-left: 20px;
  padding-right: 20px;
  .icon {
    height: 20px;
    width: 20px;
  }
  .text {
    margin-left: 10px;
    .textTop {
      font-weight: bold;
      font-size: 14px;
    }
    .textBottom {
      font-weight: bold;
      font-size: 12.5px;
      margin-top: 6px;
      .phone {
        margin-left: 10px;
      }
    }
  }
  .noText{
    font-size: 15px;
  }
  .default {
    margin-left: 15px;
    height: 20px;
    width: 40px;
    text-align: center;
    line-height: 20px;
    border-radius: 20px;
    color: #fff;
    background-color: @mainColor;
  }
  .rightIcon {
    height: 20px;
    width: 20px;
    margin-left: auto;
  }
}
.mode {
  height: 70px;
  background-color: #fff;
  padding: 0px 20px;
  display: flex;
  margin-top: 3px;
  align-items: center;
  .timeIcon {
    height: 20px;
    width: 20px;
  }
  .text {
    margin-left: 8px;
    font-weight: bold;
    font-size: 14px;
  }
  .time {
    color: @importance;
    font-weight: bold;
  }
  .rightIcon {
    height: 20px;
    width: 20px;
    margin-left: auto;
  }
}
.gift {
  height: 70px;
  background-color: #fff;
  margin-top: 10px;
  display: flex;
  padding: 0px 20px;
  align-items: center;
  .giftIcon {
    height: 20px;
    width: 20px;
  }
  .giftText {
    font-size: 14px;
    font-weight: bold;
    margin-left: 5px;
  }
  .giftPrice {
    margin-left: auto;
    color: @importance;
    font-weight: bold;
    font-size: 14px;
  }
}
.ItemsTotal {
  height: 280px;
  background-color: #fff;
  margin-top: 5px;
  box-sizing: border-box;
  padding: 20px 20px;
  .item {
    display: flex;
    margin-top: 10px;
    font-size: 12px;
    font-weight: bold;
    color: #bebebe;
    .price {
      margin-left: auto;
    }
    .discounts {
      color: @importance;
    }
    .bigPrice {
      margin-left: auto;
      font-size: 24px;
      color: black;
      display: flex;
      .small {
        font-size: 12px;
        margin-top: 2px;
      }
    }
  }
}
}
.selectPay {
  position: absolute;
}
/deep/ .van-button--large {
  top: 570px;
  height: 45px;
}
/deep/ .van-icon-edit::before {
  content: "";
}
/deep/ .van-button--danger {
  background-color: @mainColor;
  border-color: @mainColor;
}
/deep/ .van-address-list {
  position: absolute;
  width: 100%;
  top: 0px;
  bottom: 46px;
  overflow-y: auto;
}
/deep/ .van-tag--danger {
  background-color: @mainColor;
}
/deep/ .van-address-item .van-radio__icon--checked .van-icon {
  background-color: @mainColor;
  border-color: @mainColor;
}
</style>